package com.begye.smartloan.apptest.renzheng.views

import android.content.Context
import android.text.InputType
import android.util.AttributeSet
import android.view.View
import android.widget.LinearLayout
import com.begye.smartloan.apptest.R
import com.begye.smartloan.apptest.databinding.FillItemInputBinding
import com.begye.smartloan.apptest.ext.addColor
import com.begye.smartloan.apptest.tool.addTouch
import org.json.JSONObject
import kotlin.math.max

class FillItemInput : LinearLayout, IFillItemResult {

    private var _binding: FillItemInputBinding? = null
    private val binding get() = _binding!!
    private var _action: String = "INPUT"
    private var _isMust: Boolean = true

    constructor(context: Context?) : this(context, null)
    constructor(context: Context?, attrs: AttributeSet?) : this(context, attrs, 0)
    constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : this(
        context,
        attrs,
        defStyleAttr,
        0
    )

    constructor(
        context: Context?,
        attrs: AttributeSet?,
        defStyleAttr: Int,
        defStyleRes: Int,
    ) : super(
        context,
        attrs,
        defStyleAttr,
        defStyleRes
    ) {
        context?.let {
            val layout = View.inflate(it, R.layout.fill_item_input, this)
            _binding = FillItemInputBinding.bind(layout)
        }
    }

    override fun onFinishInflate() {
        super.onFinishInflate()
        // Ensure binding is not null after inflation
        if (_binding == null) {
            throw IllegalStateException("ViewBinding not initialized for ${javaClass.simpleName}")
        }
    }

    override fun onDetachedFromWindow() {
        super.onDetachedFromWindow()
        _binding = null  // Clear the binding reference
    }

    fun initDataSource(value: JSONObject) {
        val title = value.optString("title", "")
        val tag = value.optString("paramName", "")
        val hint = value.optString("hint", "")
        val action = value.optString("action", "")
        val isMust = value.optString("isMust", "YES")
        addTag(tag)
        addTitle(title)
        addHint(hint)
        addAction(action)
        addMust(isMust)

        binding.fillItemInputEdit.addBr {
            calBtw(it)
        }
    }

    fun addTag(value: String): FillItemInput {
        this.tag = value
        return this
    }

    fun addAction(value: String): FillItemInput {
        this._action = value
        return this
    }

    fun addMust(value: String = "YES"): FillItemInput {
        this._isMust = value == "YES"
        return this
    }

    fun addTitle(value: String): FillItemInput {
        binding.fillItemInputTitle.text = value
        binding.fillItemInputTitle.addColor("*", "#F55555")
        return this
    }

    fun addHint(value: String?): FillItemInput {
        binding.fillItemInputEdit.setHint(value)
        return this
    }

    fun addContent(value: String): FillItemInput {
        binding.fillItemInputEdit.setText(value)
        return this
    }

    fun addNumberInputType(): FillItemInput {
        binding.fillItemInputEdit.inputType = InputType.TYPE_CLASS_NUMBER
        return this
    }

    private fun calTag(): String {
        return (this.tag ?: "").toString().trim()
    }

    private fun calBtw(value: String) {
        try {
            addTouch(type = "INPUT_${calTag()}", remark = value)

        } catch (e: Exception) {
            //
        }
    }

    private fun calBtwUpdate(fts: Long, bts: Long, index: Int, value: String) {
        try {
            if (value.isNotBlank()) {
                val bw = max(0L, (bts - fts)).toString()
                addTouch(type = "SELECT_${calTag()}_$index", remark = "${value}$$${bw}")
            }

        } catch (e: Exception) {
            //
        }
    }

    override fun calResult(check: Boolean): String {
        val result = binding.fillItemInputEdit.text.toString().trim()
        if (check) {
            if (result.isBlank()) {
                binding.fillItemInputEdit.setBackgroundResource(R.drawable.layer_c25_fafafa_err)
            } else {
                binding.fillItemInputEdit.setBackgroundResource(R.drawable.layer_c25_fafafa)
            }
        }
        return result
    }

    override fun calAction(): String {
        return this._action
    }

    override fun updateValue(fts: Long, bts: Long, index: Int, value: String) {
        binding.fillItemInputEdit.setText(value)
        calBtwUpdate(fts, bts, index, value)
    }

    override fun isMust(): Boolean {
        return this._isMust
    }
}